package com.strive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.strive.entity.TbPermission;
import com.strive.entity.TbUser;
import com.strive.mapper.PermissionMapper;
import com.strive.mapper.UserMapper;
import com.strive.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/2/24 17:29
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public TbUser getByUserName(String username){
        return userMapper.selectOne(new QueryWrapper<TbUser>().eq("username", username));
    }

    @Override
    public String createUser(TbUser tbUser) {
        tbUser.setPassword(passwordEncoder.encode(tbUser.getPassword()));
        userMapper.insert(tbUser);
        return "ok";
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser user = this.getByUserName(username);
        List<GrantedAuthority> authorityList = new ArrayList<>();

        if(user != null){
            List<TbPermission> permissionList = permissionMapper.selectList(new QueryWrapper<TbPermission>().eq("id", user.getId()));
            permissionList.forEach(permission->{
                if(permission != null && StringUtils.isNotBlank(permission.getEnname())){
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getEnname());
                    authorityList.add(grantedAuthority);
                }
            });
            return new User(user.getUsername(),user.getPassword(),authorityList);
        }else {
            throw new UsernameNotFoundException("用户名不存在");
        }
    }
}
